package com.wisdom.core.netty.handler.server;

import com.alibaba.fastjson.JSON;
import com.wisdom.core.data.RpcResponse;
import com.wisdom.core.exception.RpcException;
import com.wisdom.core.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @description: <将响应体RpcResponse对象编码为ByteBuf  二次编码器>
 * @author: Leo
 * @date:2021-08-22 15:21
 */
@Slf4j
public class RpcResponseEncoder extends MessageToMessageEncoder<RpcResponse> {

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcResponse rpcResponse, List<Object> out) {
        try {
            //将 rpcResponse 序列化为字节数据  交由下游处理器处理
            log.info("server send response, response is {}", JSON.toJSONString(rpcResponse));
            byte[] bytes = ProtostuffUtil.serialize(rpcResponse);
            ByteBuf buffer = ctx.alloc().buffer(bytes.length);
            buffer.writeBytes(bytes);
            out.add(buffer);

        }catch (Exception e){
            log.error("RpcResponseEncoder encode rpcResponse error, msg is {}",e.getMessage());
            throw new RpcException(e.getMessage(),e);
        }
    }
}
